package com.shuyuwl.controller;

import com.shuyuwl.core.support.ServerResponse;
import com.shuyuwl.service.FileService;
import com.shuyuwl.utils.FastFileUploadUtil;
import com.shuyuwl.vo.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Tangnibal
 * @date: 2019年11月08日
 */
@RestController
@RequestMapping("/api/file")
@Api(tags = "文件管理")
@Slf4j
@CrossOrigin(allowCredentials = "true",maxAge = 3600,allowedHeaders = "*",origins = "*")
public class FileController {

    @Autowired
    private FileService service;

    @DeleteMapping
    @ApiOperation("按路径删除文件")
    public ServerResponse deleteByPath(@RequestParam("path") String path){
        try {
            FastFileUploadUtil.deleteByPath(path);
            return ServerResponse.createBySuccess("删除成功");
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("删除失败");
        }
    }

    @DeleteMapping("/{id}")
    public ServerResponse deleteById(@PathVariable("id") Long id){
        try {
            FastFileUploadUtil.deleteByFileId(id);
            return ServerResponse.createBySuccess("删除成功");
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("删除失败");
        }
    }

    @PostMapping
    @ApiOperation("文件上传")
    public ServerResponse<FileVo> uploadFile(@RequestParam("file") MultipartFile multipartFile){
        return service.uploadFile(multipartFile);
    }

    @PostMapping("/image")
    @ApiOperation("图片上传")
    public Map<String, Object> infoImage(@RequestParam("picture") MultipartFile multipartFile) {
        Map<String, Object> result = new HashMap<>();
        if (multipartFile == null) {
            result.put("message", "文件未接收到");
            return result;
        }
        String uploadPath = FastFileUploadUtil.uploadFile(multipartFile);
        List<String> data = new ArrayList<>();
        data.add(uploadPath);
        result.put("data", data);
        return result;
    }

}
